//
//  Utils.m
//  JuYouQian
//
//  Created by hisuntech on 14-12-18.
//  Copyright (c) 2014年 hisuntech. All rights reserved.
//

#import <CommonCrypto/CommonDigest.h> // Need to import for CC_MD5 access
#import <Accelerate/Accelerate.h>
#import "sys/utsname.h"
#import "Utils.h"
#import "Reachability.h"
#import "SessionMgr.h"
#import "HeConstants.h"
#import "HePreferrence.h"


@implementation Utils


+ (NSString*) deviceString
{
    // 需要#import "sys/utsname.h"
    
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    if ([deviceString isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    
    if ([deviceString isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    
    if ([deviceString isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5";
    
    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5C";
    
    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5C";
    
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5S";
    
    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    
    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    
    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    
    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    
    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
    
    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    
    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    
    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    
    if ([deviceString isEqualToString:@"iPad2,5"])      return @"iPad mini";
    
    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
    
    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
    
    NSLog(@"NOTE: Unknown device type: %@", deviceString);
    
    return deviceString;
    
}

+(int)getIphoneModel{
    enum IPHONE_MODEL model = NONE;
    
    if ([UIScreen instancesRespondToSelector:@selector(currentMode)]) {
        CGSize size = [[UIScreen mainScreen] currentMode].size;
        NSLog(@"size.w = %f   size.h = %f",size.width,size.height);
        
        if (size.height<1136) {
            if (size.width==640) {
                model = iPHONE4;
            }
            model = iPHONE4;
        }else if (size.width == 640 && size.height == 1136){
            model = iPHONE5;
        }else if (size.width ==750 && size.height == 1334){
            model = iPHONE6;
        }else if (size.width == 1242 && size.height == 2208){
            model = iPHONE6_PLUS;
        }else{
            model = iPAD_OTHER;
            model = iPHONE4;
        }
    }
    
    return model;
}

+(NSString*)getDeviceInfo{
//    NSString *strName = [[UIDevice currentDevice] name]; // Name of the phone as named by user
//    NSString *strId = [[UIDevice currentDevice] uniqueIdentifier]; // A GUID like string
//    NSString *strSysName = [[UIDevice currentDevice] systemName]; // "iPhone OS"
//    NSString *strSysVersion = [[UIDevice currentDevice] systemVersion]; // "2.2.1"
//    NSString *strModel = [[UIDevice currentDevice] model]; // "iPhone" on both devices
//    NSString *strLocModel = [[UIDevice currentDevice] localizedModel]; // "iPhone" on both devices
//    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    
    NSString *strSysVersion = [[UIDevice currentDevice] systemVersion]; // "2.2.1"
    return strSysVersion;
}

+(UIImage*)screenshot:(UIView*)viewshot {
    UIGraphicsBeginImageContext(viewshot.bounds.size);
    if( [self respondsToSelector:@selector(drawViewHierarchyInRect:afterScreenUpdates:)] ){
        [viewshot drawViewHierarchyInRect:viewshot.bounds afterScreenUpdates:YES];
    }else{
        [viewshot.layer renderInContext:UIGraphicsGetCurrentContext()];
    }
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // hack, helps w/ our colors when blurring
    NSData *imageData = UIImageJPEGRepresentation(image, 1); // convert to jpeg
    image = [UIImage imageWithData:imageData];
    
    return image;
}

+(UIImage*)ScreenShots
{
    CGSize imageSize = [[UIScreen mainScreen] bounds].size;
    if (NULL != &UIGraphicsBeginImageContextWithOptions) {
        UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0);
    }
    else
    {
        UIGraphicsBeginImageContext(imageSize);
    }
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    for (UIWindow * window in [[UIApplication sharedApplication] windows]) {
        if (![window respondsToSelector:@selector(screen)] || [window screen] == [UIScreen mainScreen]) {
            CGContextSaveGState(context);
            CGContextTranslateCTM(context, [window center].x, [window center].y);
            CGContextConcatCTM(context, [window transform]);
            CGContextTranslateCTM(context, -[window bounds].size.width*[[window layer] anchorPoint].x, -[window bounds].size.height*[[window layer] anchorPoint].y);
            [[window layer] renderInContext:context];
            
            CGContextRestoreGState(context);
        }
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    return image;
    NSLog(@"Suceeded!");
}

+(void)shakeAnimationForView:(UIView *) view{
    // 获取到当前的View
    CALayer *viewLayer = view.layer;
    // 获取当前View的位置
    CGPoint position = viewLayer.position;
    // 移动的两个终点位置
    CGPoint x = CGPointMake(position.x, position.y+0);
    CGPoint y = CGPointMake(position.x, position.y-5);
    // 设置动画
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    // 设置运动形式
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    // 设置开始位置
    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    // 设置结束位置
    [animation setToValue:[NSValue valueWithCGPoint:y]];
    // 设置自动反转
    [animation setAutoreverses:YES];
    // 设置时间
    [animation setDuration:.06];
    // 设置次数
    [animation setRepeatCount:1];
    // 添加上动画
    [viewLayer addAnimation:animation forKey:nil];
}


+(NSDateComponents*)getCalendarComponents{
    
   NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
   NSDateComponents* comps = [[NSDateComponents alloc] init];
   NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
   NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
   NSDate *now=[NSDate date];
   comps = [calendar components:unitFlags fromDate:now];
   NSInteger year =[comps year];
   NSInteger week = [comps weekday];
   NSInteger month = [comps month];
   NSInteger day = [comps day];
   NSInteger hour = [comps hour];
   NSInteger min = [comps minute];
   NSInteger sec = [comps second];
   //NSLog(@"公历 %d年-%d月-%d日 周%d hour=%d时 min=%d分 sec=%d秒",year,month,day,week-1,hour,min,sec);
   
   return comps;
}

+(Boolean)hasNetwork{
    //判断网络连接
    // BOOL isExistenceNetwork;
    //	Reachability *r = [Reachability reachabilityWithHostName:@"www.apple.com"];
    Reachability* r = [Reachability reachabilityForInternetConnection];
    NetworkStatus netStatus = [r currentReachabilityStatus];
    
    BOOL connectionRequired = [r connectionRequired];
    NSLog(@"connectionRequired==%d",connectionRequired);
    if(connectionRequired){
    }
    
    switch (netStatus) {
        case NotReachable:
            //		isExistenceNetwork=FALSE;
            NSLog(@"没有网络");
            return false;
            break;
        case ReachableViaWWAN:
            //		isExistenceNetwork=TRUE;
            NSLog(@"正在使用3G网络");
            
            return true;
            break;
        case ReachableViaWiFi:
            //		isExistenceNetwork=TRUE;
            NSLog(@"正在使用wifi网络");
            
            return true;
            break;
        default:
            NSLog(@"正在使用gprs网络");
            return false;
    }
}

//dateStr格式：20140622
//返回格式：22
+(NSString*)getDataDay:(NSString*)dateStr{
//    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\""];
//    NSString *trimmedString = [dateStr stringByTrimmingCharactersInSet:set];
    
    NSString *trimmedString = dateStr;
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@" " withString:@""];
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@":" withString:@""];
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@"-" withString:@""];
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@"_" withString:@""];
    
    NSString* day = @"";
    if ([trimmedString length]>=8) {
//        NSString* year = [dateStr substringToIndex:4];
//        NSRange range;range.location=4;range.length=2;
//        NSString* mon = [dateStr substringWithRange:range];
        day = [trimmedString substringFromIndex:6];
    }
    return day;
}

//dateStr格式：20140622
//返回格式：2014.06.22
+(NSString*)getFormatDate:(NSString*)dateStr{
    NSString* formatStr = dateStr;
    
//    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\""];
//    NSString *trimmedString = [dateStr stringByTrimmingCharactersInSet:set];

    NSString *trimmedString = dateStr;
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@" " withString:@""];
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@":" withString:@""];
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@"-" withString:@""];
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@"_" withString:@""];
    
    if ([trimmedString length]>=8) {
        NSString* year = [trimmedString substringToIndex:4];
        NSRange range;range.location=4;range.length=2;
        NSString* mon = [trimmedString substringWithRange:range];
        
        NSRange range2;range2.location=6;range2.length=2;
//        NSString* day = [dateStr substringFromIndex:6];
        NSString* day = [trimmedString substringWithRange:range2];
        formatStr = [NSString stringWithFormat:@"%@年%@月%@日",year,mon,day];
    }
    return formatStr;
}

//dateStr格式：20140622
//返回格式：2014-06-22
+(NSString*)getFormatDateH:(NSString*)dateStr{
    NSString* formatStr = dateStr;
    
    //    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\""];
    //    NSString *trimmedString = [dateStr stringByTrimmingCharactersInSet:set];
    
    NSString *trimmedString = dateStr;
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@" " withString:@""];
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@":" withString:@""];
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@"-" withString:@""];
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@"_" withString:@""];
    
    if ([trimmedString length]>=8) {
        NSString* year = [trimmedString substringToIndex:4];
        NSRange range;range.location=4;range.length=2;
        NSString* mon = [trimmedString substringWithRange:range];
        
        NSRange range2;range2.location=6;range2.length=2;
        //        NSString* day = [dateStr substringFromIndex:6];
        NSString* day = [trimmedString substringWithRange:range2];
        formatStr = [NSString stringWithFormat:@"%@-%@-%@",year,mon,day];
    }
    return formatStr;
}

//dateStr格式：20140622
//返回格式：2014年06月22日10点22分
+(NSString*)getFormatDateTime:(NSString*)dateStr{
    
//    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"@／：；（）¥「」＂、[]{}#%-*+=_\\|~＜＞$€^•'@#$%^&*()_+'\""];
//    NSString *trimmedString = [dateStr stringByTrimmingCharactersInSet:set];
    
    NSString *trimmedString = dateStr;
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@" " withString:@""];
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@":" withString:@""];
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@"-" withString:@""];
    trimmedString = [trimmedString stringByReplacingOccurrencesOfString:@"_" withString:@""];
    
    NSString* formatStr = dateStr;
    if ([trimmedString length]>=12) {
        NSString* year = [trimmedString substringToIndex:4];
        NSRange range;range.location=4;range.length=2;
        NSString* mon = [trimmedString substringWithRange:range];
        NSRange range2;range2.location=6;range2.length=2;
        NSString* day = [trimmedString substringWithRange:range2];
        NSRange range3;range3.location=8;range3.length=2;
        NSString* hour = [trimmedString substringWithRange:range3];
        NSRange range4;range4.location=10;range4.length=2;
        NSString* min = [trimmedString substringWithRange:range4];
        
        formatStr = [NSString stringWithFormat:@"%@年%@月%@日%@点%@分",year,mon,day,hour,min];
    }else{
        formatStr = [Utils getFormatDate:dateStr];
    }
    return formatStr;
}

//返回格式：201406221111
+(NSString*)getFormatCurrDate{

    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
//    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
    //用[NSDate date]可以获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];
    //输出格式为：2010-10-27 10:22:13
    NSLog(@"%@",currentDateStr);
    
    return currentDateStr;
}

+(void)clearLoginCookie{
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]) {
        [storage deleteCookie:cookie];
    }
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    //    [cache setDiskCapacity:0];
    //    [cache setMemoryCapacity:0];
    
    NSArray *nowcookies= [NSArray array];
    NSLog(@"clearLoginCookie  %@",nowcookies);
    //////缓存
    NSData *encodednowcookies = [NSKeyedArchiver archivedDataWithRootObject:nowcookies];
    [HePreferrence setValue:encodednowcookies forKey:@"cookies"];
}

+(void)saveLoginCookies{
    NSArray *nowcookies=[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    NSLog(@"登录成功 nowcookies  %@",nowcookies);
    //////缓存
    NSData *encodednowcookies = [NSKeyedArchiver archivedDataWithRootObject:nowcookies];
    [HePreferrence setValue:encodednowcookies forKey:@"cookies"];
}

+(void)setViewBorder:(UIView*)view radius:(CGFloat)radius borderColor:(UIColor*)borderColor{
    view.layer.masksToBounds = YES;
    [view.layer setCornerRadius:radius];
    [view.layer setBorderColor:borderColor.CGColor];
    [view.layer setBorderWidth:0.5];
}

+(void)setViewBorder:(UIView*)view radius:(CGFloat)radius borderColor:(UIColor*)borderColor borderW:(float)width{
    view.layer.masksToBounds = YES;
    [view.layer setCornerRadius:radius];
    [view.layer setBorderColor:borderColor.CGColor];
    [view.layer setBorderWidth:width];
}

//ios 判断字符串为空和只为空格解决办法
+(NSString*)isBlankString:(NSString *)string{
    NSString* returnString = @"";
    
    if (string != nil
        &&string != NULL
        &&![string isKindOfClass:[NSNull class]]
        &&![[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        returnString = string;
    }
    
    return returnString;
}


+(BOOL)containsChinese:(NSString *)str {
    for(int i = 0; i < [str length]; i++) {
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
            return TRUE;
    }
    return FALSE;
}


+(NSString*)getLimitTypeData:(NSString*)limitType data:(NSString*)limiteData{
    int type = [limitType intValue];
    NSString* text = @"";
    switch (type) {
        case 0:
            text = [NSString stringWithFormat:@"%@天",limiteData];
            break;
        case 1:
            text = [NSString stringWithFormat:@"%@天",limiteData];
            break;
        case 2:
            text = [NSString stringWithFormat:@"%@周",limiteData];
            break;
        case 3:
            text = [NSString stringWithFormat:@"%@个月",limiteData];
            break;
        case 4:
            text = [NSString stringWithFormat:@"%@天",limiteData];
            break;
        default:
            text = [NSString stringWithFormat:@"%@天",limiteData];
            break;
    }

    return text;
}

+(NSString*)getProVendorName:(NSString*)vendorCode{
    NSString* proVendor = @"";
    if ([vendorCode isEqualToString:@"JF"]) {
        proVendor = @"玖富";
    }
    return proVendor;
}

//orderStatus	Max(2)	String	U.订单已登记S.订单已支付R.订单已赎回F.订单作废D:待支付P:赎回待确认
+(NSString*)getOrderStatus:(NSString*)strOrderStatus{
    NSString* text = @"";
    if ([strOrderStatus isEqualToString:@"U"]) {
        text = @"支付处理中";
    }else if ([strOrderStatus isEqualToString:@"S"]) {
        text = @"购买成功";
    }else if ([strOrderStatus isEqualToString:@"R"]) {
        text = @"已提现";
    }else if ([strOrderStatus isEqualToString:@"F"]) {
        text = @"已作废";
    }else if ([strOrderStatus isEqualToString:@"D"]) {
        text = @"支付处理中";
    }else if ([strOrderStatus isEqualToString:@"P"]) {
        text = @"提现处理中";
    }
    return text;
}

+(UIColor*)getOrederStatusColor:(NSString*)strOrderStatus{
    UIColor* backColor;
    if ([strOrderStatus isEqualToString:@"U"]) {
        //            text = @"已提交";
        backColor = [UIColor colorWithRed:245/255.0 green:184/255.0 blue:35/255.0 alpha:1];//黄色
    }else if ([strOrderStatus isEqualToString:@"S"]) {
        //            text = @"已支付";
        backColor = [UIColor colorWithRed:135/255.0 green:169/255.0 blue:118/255.0 alpha:1];//绿色
    }else if ([strOrderStatus isEqualToString:@"R"]) {
        //            text = @"已赎回";
        backColor = [UIColor colorWithRed:135/255.0 green:169/255.0 blue:118/255.0 alpha:1];//绿色
    }else if ([strOrderStatus isEqualToString:@"F"]) {
        //            text = @"已作废";
        backColor = UIBaseColor;//红色
    }else if ([strOrderStatus isEqualToString:@"D"]) {
        //            text = @"待支付";
        backColor = [UIColor colorWithRed:245/255.0 green:184/255.0 blue:35/255.0 alpha:1];//黄色
    }else if ([strOrderStatus isEqualToString:@"P"]) {
        //            text = @"赎回待确认";
        backColor = [UIColor colorWithRed:245/255.0 green:184/255.0 blue:35/255.0 alpha:1];//黄色
    }
    return backColor;
}

+(NSString *)phoneNumberFormart:(NSString *)phoneNumber{
    
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";//移动电话 移动，联通，电信
    
    NSString * PHS = @"^(01[0-9]|02[0-9]|0[3-9][0-9]{2})?([2-9][0-9]{6,7})+(\\[0-9]{1,4})?$";//固话（不包括港澳台）
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    NSPredicate *regextestphs= [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];
    
    if ([regextestmobile evaluateWithObject:phoneNumber] == YES)
    {
        NSMutableString *newNum = [NSMutableString string];
        
        [newNum appendString:[phoneNumber substringWithRange:NSMakeRange(0, 3)]];
        
        [newNum appendString:@"-"];
        
        [newNum appendString:[phoneNumber substringWithRange:NSMakeRange(3, 4)]];
        
        [newNum appendString:@"-"];
        
        [newNum appendString:[phoneNumber substringWithRange:NSMakeRange(7, 4)]];
        
        return newNum;
        
    }else if([regextestphs evaluateWithObject:phoneNumber] == YES){
        
        int len = 0;
        
        if ([[phoneNumber substringWithRange:NSMakeRange(0, 2)] isEqualToString:@"01"] ||
            [[phoneNumber substringWithRange:NSMakeRange(0, 2)] isEqualToString:@"02"]) {
            
            len = 3;
            
        }else{
            
            len = 4;
            
        }
        
        NSMutableString *newNum = [NSMutableString string];
        
        [newNum appendString:[phoneNumber substringWithRange:NSMakeRange(0, len)]];
        
        [newNum appendString:@"-"];
        
        [newNum appendString:[phoneNumber substringWithRange:NSMakeRange(len, phoneNumber.length - len)]];
        
        return newNum;
        
    }else
    {
        
        return @"格式不对";
        
    }
    
}

// 正则判断手机号码地址格式
+(BOOL)isMobileNumber:(NSString *)mobileNum{
    
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,183,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     * 虚拟：170
     */
    //    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[0235-9])\\d{8}$";
    NSString * MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|7[0]|8[0-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,183,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[12378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNum] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES))
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

+(NSString *)CheckIDNoForCreaditCard:(NSString*)idNo {
    
    NSString* errStr = @"";
    if ([idNo length] != 18) {
        errStr =  NSLocalizedString(@"id card number digits mistake", nil);
        return errStr;
    }
    
    int mm = 0;
    int gg[18] = {0};
    
    NSString* M = idNo;
    
    int xx[] = { 2, 4, 8, 5, 10, 9, 7, 3, 6, 1, 2, 4, 8, 5, 10, 9, 7 };
    char yy[] = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };
    
    for (int i = 1; i < 18; i++) {
        int j = 17 - i;
        NSRange rng = NSMakeRange(j, 1);
        gg[i-1] = [[M substringWithRange:rng]intValue];
    }
    
    for (int i = 0; i < 17; i++) {
        mm += xx[i] * gg[i];
    }
    mm = mm % 11;
    char c = [M characterAtIndex:17];
    
    if (c == yy[mm]) {
        return errStr;
    }
    else {
        errStr =  NSLocalizedString(@"id number is wrong", nil);
        return errStr;
    }
}

//邮箱
+ (BOOL)ValidateEmail:(NSString *)email{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

//用户名
+ (BOOL)ValidateUserName:(NSString *)name{
    NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
}

//密码
+ (BOOL)ValidatePassword:(NSString *)passWord{
    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}

//判断是否包含
+ (BOOL) judgeRange:(NSArray*) _termArray Password:(NSString*) _password
{
    NSRange range;
    BOOL result =NO;
    for(int i=0; i<[_termArray count]; i++)
    {
        range = [_password rangeOfString:[_termArray objectAtIndex:i]];
        if(range.location != NSNotFound)
        {
            result =YES;
        }
    }
    return result;
}

//条件
+ (int) judgePasswordStrength:(NSString*) _password
{
    NSMutableArray* resultArray = [[NSMutableArray alloc] init];
    
    NSArray* termArray1 = [[NSArray alloc] initWithObjects:@"a", @"b", @"c", @"d", @"e", @"f", @"g", @"h", @"i", @"j", @"k", @"l", @"m", @"n", @"o", @"p", @"q", @"r", @"s", @"t", @"u", @"v", @"w", @"x", @"y", @"z", nil];
    
    NSArray* termArray2 = [[NSArray alloc] initWithObjects:@"1", @"2", @"3", @"4", @"5", @"6", @"7", @"8", @"9", @"0", nil];
    
    NSArray* termArray3 = [[NSArray alloc] initWithObjects:@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z", nil];
    
    NSArray* termArray4 = [[NSArray alloc] initWithObjects:@"~",@"`",@"@",@"#",@"$",@"%",@"^",@"&",@"*",@"(",@")",@"-",@"_",@"+",@"=",@"{",@"}",@"[",@"]",@"|",@":",@";",@"“",@"'",@"‘",@"<",@",",@".",@">",@"?",@"/",@"、", nil];
    NSString* result1 = [NSString stringWithFormat:@"%d",[self judgeRange:termArray1 Password:_password]];
    NSString* result2 = [NSString stringWithFormat:@"%d",[self judgeRange:termArray2 Password:_password]];
    NSString* result3 = [NSString stringWithFormat:@"%d",[self judgeRange:termArray3 Password:_password]];
    NSString* result4 = [NSString stringWithFormat:@"%d",[self judgeRange:termArray4 Password:_password]];
    [resultArray addObject:[NSString stringWithFormat:@"%@",result1]];
    [resultArray addObject:[NSString stringWithFormat:@"%@",result2]];
    [resultArray addObject:[NSString stringWithFormat:@"%@",result3]];
    [resultArray addObject:[NSString stringWithFormat:@"%@",result4]];
    int intResult=0;
    for (int j=0; j<[resultArray count]; j++)
    {
        if ([[resultArray objectAtIndex:j] isEqualToString:@"1"])
        {
            intResult++;
        }
    }
//    NSString* resultString = [[NSString alloc] init];
//    if (intResult <2)
//    {
//        resultString = @"密码强度低，建议修改";
//    }
//    else if (intResult == 2&&[_password length]>=6)
//    {
//        resultString = @"密码强度一般";
//    }
//    else if (intResult > 2&&[_password length]>=6)
//    {
//        resultString = @"密码强度高";
//    }
    return intResult;
}

+(NSString *)MD5:(NSString *)str{
    /*
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
     */
    const char *original_str = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, strlen(original_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
    {
        [hash appendFormat:@"%02x", result[i]];
    }
//    NSString *mdfiveString = [hash lowercaseString];
    NSString *mdfiveString = [hash uppercaseString];
    
    return mdfiveString;
}

+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}


+ (NSString *)SHA1:(NSString *)str {
    //    const char *cStr = [str UTF8String];
    //    NSData *data = [NSData dataWithBytes:cStr length:str.length];
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, data.length, digest);
    
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x", digest[i]];
    }
    
    return result;
}

@end
